package com.example.zhu95.mytimber.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Comparator;

/**
 * @author zhu95
 * @date 2018/3/25 17:33
 */

public class MyComparator implements Comparator<Object> {
    private Field field;
    private Method method;
    private boolean reverse = false;

    public MyComparator(Field field) {
        this.field = field;
    }

    public MyComparator(Field field, boolean reverse) {
        this.field = field;
        this.reverse = reverse;
    }

    public MyComparator(Method method) {
        this.method = method;
    }

    public MyComparator(Field field, Method method) {
        this.field = field;
        this.method = method;
    }

    @Override
    public int compare(Object o1, Object o2) {
        try {
            if (field != null) {
                field.setAccessible(true);
                Object v1 = field.get(o1);
                Object v2 = field.get(o2);
                if (v1 instanceof String) {
                    String s1 = (String) v1;
                    String s2 = (String) v2;
                    if (reverse) {
                        return -(s1.compareToIgnoreCase(s2));
                    }
                    return s1.compareToIgnoreCase(s2);
                } else if (v1 instanceof Integer) {
                    Integer num1 = (Integer) v1;
                    Integer num2 = (Integer) v2;
                    if (reverse) {
                        return -(num1.compareTo(num2));
                    }
                    return num1.compareTo(num2);
                }
            } else if (method != null) {
                method.setAccessible(true);
                Object v1 = method.invoke(o1);
                Object v2 = method.invoke(o2);
                if (v1 instanceof String) {
                    String s1 = (String) v1;
                    String s2 = (String) v2;
                    if (reverse) {
                        return -(s1.compareToIgnoreCase(s2));
                    }
                    return s1.compareToIgnoreCase(s2);
                } else if (v1 instanceof Integer) {
                    Integer num1 = (Integer) v1;
                    Integer num2 = (Integer) v2;
                    if (reverse) {
                        return -(num1.compareTo(num2));
                    }
                    return num1.compareTo(num2);
                }
            }
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
